const Base64 = require('../../crypto/Base64.js');

require('../../crypto/hmac.js');
require('../../crypto/sha1.js');
const Crypto = require('../../crypto/crypto.js');

var app = getApp();
var https = "https://www.moreclub.cn/";
var http1 = 'http://10.150.7.248:8001/'
var http2 = 'http://59.110.53.149:8088/'

// var uploadAliyun = require('./uploadAliyun.js');
var imgurl;
var vale;
var city;
var nametxt;
var midtxt;
var pwd;
var mid;
var arr;
var tid;
var picurlarr = []


var random_string = function(len){
  //len = len || 32;
  var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var maxPos = chars.length;
  pwd = '';
  for (var i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  //return pwd;
  console.log(pwd)
}


Page({
  data:{

  },
  onShow:function(){
    var that = this
   
    wx.getSystemInfo({
      success: (res) => {
        let ww = res.windowWidth;
        let wh = res.windowHeight;
        let scrollH = wh;
        console.log(scrollH)

        this.setData({
          scrollH: scrollH,
          w: ww,
          wh: wh
        });

      }
    })

    nametxt = app.globalData.nametxt
    if (app.globalData.midtxt){
      mid = app.globalData.midtxt
    }else{
      mid == '' || mid ==null
    }
    if (app.globalData.tidtxt){
      tid = app.globalData.tidtxt
    }else{
      tid = 0
    }
   
    var huati = app.globalData.huati
    that.setData({
      nametxt: nametxt,
      midtxt: mid,
      huati:huati
    })
   

   
  },
  onLoad:function(){
    var that = this;
    var uid = wx.getStorageSync('uid');
   
    city = wx.getStorageSync('city');
    var lat1 = wx.getStorageSync('lat1');
    var lng1 = wx.getStorageSync('lng1');
    if (city == '' || !city|| typeof (city) == "undefined") {
      city = 'cd'
    }
    if (lat1 == '' || !lat1 || typeof (lat1) == "undefined"){
      lat1 = '30.632938'
    }
    if (lng1 == '' || !lng1 || typeof (lng1) == "undefined") {
      lng1 = '104.054685'
    }
   
    wx.request({
      url: https + 'v1/merchant/open/nearby/' + city,
      // dataType: "json",
      data: {
        pn: 0,
        ps: 5,
        //location: '104.054685,30.632938'
        location: lng1 + ',' + lat1
      },
      success:function(res){
        console.log(res)
      
         var resData = res.data.data
 
        that.setData({
          resData: resData
        })
      }
    })  

   
  },
  onUnload:function(){
    app.globalData.nametxt == null 
    app.globalData.midtxt == null 
    app.globalData.tidtxt == null
    try {
      wx.removeStorageSync('idn')
      wx.removeStorageSync('idn1')
    } catch (e) {
    }
    
  },

  num:function(e){
    var that = this
    vale = e.detail.value
 
      that.setData({
        vale: vale
      })
    
  },
  bur: function (e) {
    var that = this;
    vale = e.detail.value

      that.setData({
        vale: vale
      })
    
  },

  add_album:function(){
    var that = this;
    var uid = wx.getStorageSync('uid');
  
    var myDate = new Date();
    var year = myDate.getFullYear();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate();
    

    var access_token = wx.getStorageSync('inToken');
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: function (res) {
        console.log(res)
        imgurl = res.tempFilePaths
        console.log(imgurl)
        that.setData({
          imgurl:imgurl
        })
        
        for (var k = 0; k < imgurl.length; k++){
            random_string(12)
           //var file = imgurl[k].replace('wxfile://', '')      
            var fileW = year + '/' + month + '/' + day + '/' + uid + '' + pwd + '.jpg'
           //var fileW = year + '/' + month + '/' + day + '/' + file 
            
            var successCB
            var errorCB
        
          uploadFile(imgurl[k], fileW, successCB, errorCB)
          

        }
      
      }
    })

   
  },
pub_btn:function(){
  var that = this;
  var uid = wx.getStorageSync('uid');
  var access_token = wx.getStorageSync('inToken');
  var cityId = wx.getStorageSync('cityId');
 
  if (cityId == '' || !cityId || typeof (cityId) == "undefined") {
    cityId = '2'
  }
  console.log('picurlarr', picurlarr)
  var tidarr = []
  tidarr.push(tid)

     //发布
     if(vale){
       wx.request({
         url: https + 'v2/ugc/add?access_token=' + access_token,
         method: 'POST',
         header: {
           'content-type': 'application/json'
         },
         data: {
           "chainInters": tidarr,
           "content": vale,
           "mediaType": 1,
           "mid": mid,
           "mediaUrl": null,
           "pictures": picurlarr,
           "titlePicture": "",
           "uid": uid,
           "city": cityId
         },
         
         success: function (res) {
           console.log(res)
           picurlarr.splice(0, picurlarr.length);
           vale = "";
          wx.redirectTo({
            url: '../publish/publish'
          })
          //picurlarr.splice(0, picurlarr.length);
         
         }
       })

     }
  
},

  swich_local:function(){
    wx.navigateTo({
      url: '../location/location'
    })
  },
  swich_tag:function(){
    wx.navigateTo({
      url: '../theme/theme'
    })
  }

})



const uploadFile = function (filePath, fileW, successCB, errorCB) {
 

  // console.log('上传视频…');
  //const aliyunFileKey = fileW+filePath.replace('wxfile://', '')

  //const aliyunFileKey = fileW + '' + (new Date().getTime()) + '_' + objectId + '.mp4';
 // const aliyunServerURL = env.aliyunServerURL;
  //const accessid = env.accessid;
  const aliyunFileKey = fileW
  const policyBase64 = getPolicyBase64();
  const signature = getSignature(policyBase64);


  //console.log('aliyunFileKey=', aliyunFileKey);
 
  wx.uploadFile({
    url: 'http://more-user.oss-cn-beijing.aliyuncs.com',
    filePath: filePath,
    name: 'file',
    formData: {
      'key': aliyunFileKey,
      'OSSAccessKeyId': 'LTAIvuH0L4iRT9wE',
      'policy': policyBase64,
      'Signature': signature,
      'success_action_status': '200',
    },
    success: function (res) {
      // if (res.statusCode != 200) {
      //   errorCB(new Error('上传错误:' + JSON.stringify(res)))
      //   return;
      // }
      // console.log('上传视频成功', res)
      // successCB(aliyunFileKey);
      //console.log(res)
     
      if (res.statusCode==200){
        var picurl = 'http://more-user.oss-cn-beijing.aliyuncs.com/' + aliyunFileKey;
       
          picurlarr.push(picurl)
        
       
      }
      

    },
    fail: function (err) {
      err.wxaddinfo = aliyunServerURL;
      errorCB(err);
    },
  })
}

const getPolicyBase64 = function () {
  let date = new Date();
  date.setHours(date.getHours());
  let srcT = date.toISOString();
  const policyText = {
    "expiration": "2020-01-01T12:00:00.000Z",
    "conditions": [
      ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
    ]
  };

  const policyBase64 = Base64.encode(JSON.stringify(policyText));
  return policyBase64;
}

const getSignature = function (policyBase64) {
  const accesskey = 'BcNFpRkba9n777qyd1FTGmQUM3Vl62';

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = Crypto.util.bytesToBase64(bytes);

  return signature;
}

// module.exports = uploadFile;